



from rest_framework import serializers




#卿凌 --3.1 频道列表序列化器
from articles.models import Article, Comment
from questions.models import Label
from users.models import User



#处理嵌套的Article
class ArticlesBSeriliazer(serializers.ModelSerializer):

    class Meta:
        model = Article
        fields = ("id","title")


#处理嵌套的user字段序列化器
class UserDetailSerializer(serializers.ModelSerializer):

    articles = ArticlesBSeriliazer(read_only=True, many=True)

    class Meta:
        model = User
        fields = ('id', 'username','avatar','articles','fans')

class ChannelsSerializer(serializers.Serializer):

    id = serializers.IntegerField(read_only=True)
    name = serializers.StringRelatedField()



#卿凌 --3.2 文章列表序列化器，
class ArticleListSerializer(serializers.ModelSerializer):
    user = UserDetailSerializer(read_only=True)
    collected = serializers.BooleanField(default=False)

    class Meta:
        model = Article
        fields = ("id", "title", "content", "createtime", "user", "collected_users", "collected", "image", "visits")

#卿凌 --3.4 文章详情
class CommentSerializerItem(serializers.ModelSerializer):
    user = UserDetailSerializer(read_only=True)
    subs = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    class Meta:
        model = Comment
        fields = ('id', 'content','article','user','parent','subs','createtime')

class CommentSerializerList(serializers.ModelSerializer):
    user = UserDetailSerializer(read_only=True)
    subs = CommentSerializerItem(read_only=True, many=True)

    class Meta:
        model = Comment
        fields = "__all__"

class ArticleDetailSerializer(serializers.ModelSerializer):
    users = UserDetailSerializer(read_only=True)
    comments = CommentSerializerList(many =True,read_only=True)
    class Meta:
        model = Article
        fields = "__all__"

#卿凌  --3.5发表文章

class LabelsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = ("id","label_name")


class ArticleCreateSerializer(serializers.ModelSerializer):
    image = serializers.CharField(required=False, default='', allow_blank=True)

    class Meta:
        model = Article

        fields = ("content", "labels", "title", "image", "channel")

class ArticleSerializerForCreate(serializers.ModelSerializer):
    image = serializers.CharField(required=False, default='',allow_blank=True)

    class Meta:
        model = Article
        exclude = ('collected_users',)



#卿凌 --3.6评论
class CommentSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = Comment
        fields = ('id', 'content','article','user','parent','createtime')